import {
    Component,
    ViewChild,
    Injector,
    Output,
    EventEmitter,
    ElementRef
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
    LocationServiceProxy,
    CreateOrUpdateLocationOfMaterialInput,
    LocationOfMaterialEditDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditLocationModal',
    templateUrl: './create-or-edit-location-modal.component.html'
})
export class CreateOrEditLocationModalComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    //location = new CreateOrUpdateLocationOfMaterialInput();
    location = new LocationOfMaterialEditDto();
    id = '';
    displayName = '';
    pid = '';
    constructor(
        injector: Injector,
        private _locationService: LocationServiceProxy
    ) {
        super(injector);
    }

    show(id?: string, pid?: string, displayName?: string): void {
        this.active = true;
        this.id = id;
        this.pid = pid;
        this.displayName = displayName;
        this._locationService.getLocationForEdit(id).subscribe(result => {
            this.location = result.locationOfMaterial;
            if (pid != null) {
                this.location.parentId = pid;
            }
            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;
        this.location.deptId = 51;
        var loc = new CreateOrUpdateLocationOfMaterialInput();
        loc.locationOfMaterial = this.location;
        if (this.pid !== undefined) {
            loc.locationOfMaterial.displayName =
                this.displayName + '-' + this.location.displayName;
        }

        this._locationService
            .createOrUpdateAreas(loc)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit();
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
